import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { getMessageInfo } from './status'
import { BaseResponse } from './types'

const service: AxiosInstance = axios.create({
    // 启用 mock 就请求 mock 路径
    // 不启用 mock 就请求 正常后端路径
    baseURL: import.meta.env.VITE_APP_USE_MOCK ? import.meta.env.VITE_APP_MOCK_BASEURL : import.meta.env.VITE_APP_API_BASEURL,
    timeout: 5000
})

// axios实例拦截请求
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)

// axios实例拦截响应
service.interceptors.response.use(
    (response: AxiosResponse) => {
        if (response.status === 200) {
            return response
        }
        ElMessage({
            message: getMessageInfo(response.status),
            type: 'error'
        })
        return response
    },
    (error: any) => {
        const { response } = error
        if (response) {
            // 请求已发出，但是不在2xx的范围
            ElMessage({
                message: getMessageInfo(response.status),
                type: 'error'
            })
            return Promise.reject(response.data)
        }
        ElMessage({
            message: '网络异常,请稍后再试!',
            type: 'error'
        })
    }
)

/**
 * 请求工具实例
 * @param config 请求配置信息
 * @returns
 */
export const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<T> => {
    const conf = config
    return new Promise((resolve, reject) => {
        service.request<any, AxiosResponse<BaseResponse>>(conf).then((res: AxiosResponse<BaseResponse>) => {
            const data = res.data
            if (data.code !== 0) {
                ElMessage({ message: data.message, type: 'error' })
                reject(data.message)
            } else {
                resolve(data.data as T)
            }
        })
    })
}

export default requestInstance
